package com.we823.cms.common.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import com.we823.cms.common.WebConstants;
import com.we823.cms.core.data.GlobalData;
import com.we823.cms.model.sys.Config;
import com.we823.cms.repository.service.sys.ConfigService;

public class FrontUtils {

	public Config getCurrentConfigModel() {
		Config configModel = GlobalData.getCurrentConfig();
		if(configModel==null){
			configModel = getConfigs();
			if(configModel!=null){
				GlobalData.setCurrentConfig(configModel);
			}
		}
		return configModel;
	}

	private Config getConfigs(){
		List<Config> configs = new ArrayList<>();
		configs = configService.findByIsCurrent(1);
		if(configs!=null && configs.size()>0){
			return configs.get(0);
		}
		return null;
	}
	
	public static Config getCurrentConfigModel(Model model){
		if(model!=null){
			Config configModel = (Config) model.asMap().get(WebConstants.CONFIG_KEY);
			return configModel;
		}else{
			return null;
		}
	}
	
	public static String getTheme(Model model){
		Config configModel = FrontUtils.getCurrentConfigModel(model);
		if(configModel!=null){
			return configModel.getCurrentTheme();
		}else{
			return "default";
		}
	}
	
	public static String getIndex(Model model){
		String index = "index";
		Config configModel = FrontUtils.getCurrentConfigModel(model);
		if(configModel!=null){
			index = configModel.getIndex();
		}
		return index;
	}
	
	public static String buildIndexTemplateUrl(String baseUrl, Model model) {
		String templateUrl = baseUrl+"%s/%s";
		model.addAttribute("isIndex",true);
		return templateUrl;
	}
	
	public static String buildTemplateUrl(String baseUrl, String templateName) {
		return baseUrl+"%s/"+templateName;
	}
	@Autowired
	private ConfigService configService;

	public ConfigService getConfigService() {
		return configService;
	}

	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}

	public void refresh() {
		Config configModel = this.getConfigs();
			GlobalData.setCurrentConfig(configModel);
	}

	
	
	
	
}
